package com.group15.phms;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.group15.phms.DeleteDialogFragment.DeleteDialogListener;
import com.group15.phms.AddNewDialogFragment.AddNewDialogListener;

import android.util.TypedValue;
import android.view.View;
import android.os.Bundle;
import android.app.DialogFragment;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.text.InputType;

public class MedicationInfo extends ListActivity implements DeleteDialogListener , AddNewDialogListener {
	SharedPreferences logins;
	DatabaseHelper db;
	ArrayAdapter<String> adapter;
	String currentUser;
	List<Dose> doses;
	List<String> doseStrings;
	ListView doseList;
	Dose deleteDose;
	String genericName;
	Medication m;
	ActionMode mActionMode;
	int flag = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_medication_info);
		// Show the Up button in the action bar.
		setupActionBar();
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());
		
		genericName = getIntent().getStringExtra("genName");
		m = db.getMedicationInfo(genericName, currentUser);
		setTitle("Details for: " + m.getName());
		
		TextView t=(TextView)findViewById(R.id.medName);
		t.setText(m.getName());
		t=(TextView)findViewById(R.id.genName);
		t.setText(m.getGenName());
		
		doses = db.getDoses(currentUser, m.getGenName());
		doseStrings = new ArrayList<String>();
		for(Dose d : doses)
		{
			doseStrings.add(d.toString());
		}
		doseStrings.add("<Tap to add new dose>");
		adapter = new ArrayAdapter<String>(  this, 
                android.R.layout.simple_list_item_1,
                doseStrings
            );
		doseList=(ListView)findViewById(android.R.id.list);
		doseList.setAdapter(adapter);
		
		
		//enable long click functionality to delete doses
		doseList.setLongClickable(true);
		doseList.setOnItemLongClickListener(new OnItemLongClickListener() {
		    public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		    	if (position<parent.getCount()-1)
		    	{
			    	DialogFragment f = new DeleteDialogFragment();
			        f.show(getFragmentManager(), "DeleteDialogFragment");
			        deleteDose = doses.get(position);
			        return true;
		    	}
		    	return false;
		    }
		});
		
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}
	
	
	//enable list clicks to add a new dose
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        if(position==l.getCount()-1)
        {
        	DialogFragment f = new AddNewDialogFragment();
            f.show(getFragmentManager(), "AddDoseDialogFragment");
        }	
    }


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.medication_info, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		case R.id.action_search:
			intent = new Intent(this, Search.class);
	    	startActivity(intent);
			return true;
		case R.id.editbutton:
			editFields();
			return true;
		case R.id.addbutton:
			DialogFragment f = new AddNewDialogFragment();
            f.show(getFragmentManager(), "AddDoseDialogFragment");
            return true;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	//delete a dose
	@Override
	public void onPositiveClick()
	{
		db= new DatabaseHelper(getApplicationContext());
		db.deleteDose(deleteDose, currentUser, genericName);
		MedicationMonitor mm = new MedicationMonitor();
 	    mm.deleteNotification(m, deleteDose, this);
		Toast.makeText(getApplicationContext(),"Dose deleted successfully", Toast.LENGTH_SHORT).show();
		doses = db.getDoses(currentUser, genericName);
		doseStrings = new ArrayList<String>();
		for(Dose d : doses)
		{
			doseStrings.add(d.toString());
		}
		doseStrings.add("Tap + to add a new dose");
		adapter = new ArrayAdapter<String>(  this, 
                android.R.layout.simple_list_item_1,
                doseStrings
            );
		doseList=(ListView)findViewById(android.R.id.list);
		doseList.setAdapter(adapter);
		doseList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
		db.closeDB();
	}
	
	//edit medication name and generic name
	void editFields()
	{

        // Start the CAB using the ActionMode.Callback defined above
        mActionMode = this.startActionMode(mActionModeCallback);
        customizeActionModeCloseButton();

		LinearLayout ll = (LinearLayout)findViewById(R.id.medInfoLayout);
		int index = ll.indexOfChild(findViewById(R.id.medName));
		ll.removeViewAt(index);
		
		EditText medName=new EditText(this);
		medName.setTextColor(Color.BLACK);
		medName.setBackgroundResource(R.drawable.edittext_modified_states);
		medName.setText(m.getName());
		medName.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
		medName.requestFocus();
		medName.setId(1);
        try {
	        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
	        mCursorDrawableRes.setAccessible(true);
	        mCursorDrawableRes.set(medName, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
	    } catch (Exception e) {}
        ll.addView(medName,index);
        
        index = ll.indexOfChild(findViewById(R.id.genName));
		ll.removeViewAt(index);
		
		EditText medGenName=new EditText(this);
		medGenName.setTextColor(Color.BLACK);
		medGenName.setBackgroundResource(R.drawable.edittext_modified_states);
		medGenName.setText(m.getGenName());
		medGenName.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
		medGenName.setId(2);
        try {
	        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
	        mCursorDrawableRes.setAccessible(true);
	        mCursorDrawableRes.set(medGenName, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
	    } catch (Exception e) {}
        ll.addView(medGenName,index);
	}
	
	//handle clicks on contextual action bar
	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

	    // Called when the action mode is created; startActionMode() was called
	    @Override
	    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
	        // Inflate a menu resource providing context menu items
	        MenuInflater inflater = mode.getMenuInflater();
	        inflater.inflate(R.menu.edit_context_menu, menu);
	        return true;
	    }

	    // Called each time the action mode is shown. Always called after onCreateActionMode, but
	    // may be called multiple times if the mode is invalidated.
	    @Override
	    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
	        return false; // Return false if nothing is done
	    }

	    // Called when the user selects a contextual menu item
	    @Override
	    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
	        switch (item.getItemId()) {
	            case R.id.done_editing:
	                applyChanges();
	                flag=1;
	                mode.finish(); // Action picked, so close the CAB
	                return true;
	            default:
	                return false;
	        }
	    }
        
	    // Called when the user exits the action mode
	    @Override
	    public void onDestroyActionMode(ActionMode mode) {
	        if (flag==1)
	        {
	        	//System.out.println("things were changed. do nothing here");
	    		mActionMode = null;
	        }
	    	else
	    	{
	    		//System.out.println("cancel clicked. keep original values");
	    		LinearLayout ll = (LinearLayout)findViewById(R.id.medInfoLayout);
	    		int index = ll.indexOfChild(findViewById(1));
	    		ll.removeViewAt(index);
	    		TextView medName = new TextView(getApplicationContext());
	    		medName.setId(R.id.medName);
	    		medName.setText(m.getName());
	    		medName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
	    		ll.addView(medName,index);
	    		index = ll.indexOfChild(findViewById(2));
	    		ll.removeViewAt(index);
	    		TextView medGenName = new TextView(getApplicationContext());
	    		medGenName.setId(R.id.genName);
	    		medGenName.setText(m.getGenName());
	    		medGenName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
	    		ll.addView(medGenName,index);
	    		mActionMode = null;
	    	}
	    	flag=0;
	    }
	};

	//save changes to medicine name and generic name
	void applyChanges()
	{
		LinearLayout ll = (LinearLayout)findViewById(R.id.medInfoLayout);
		int index = ll.indexOfChild(findViewById(1));
		EditText e = (EditText) ll.findViewById(1);
		String textname = e.getText().toString();
		ll.removeViewAt(index);
		TextView medName = new TextView(this);
		medName.setId(R.id.medName);
		medName.setText(textname);
		medName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
		ll.addView(medName,index);
		
		index = ll.indexOfChild(findViewById(2));
		e = (EditText) ll.findViewById(2);
		String textgenname = e.getText().toString();
		ll.removeViewAt(index);
		TextView medGenName = new TextView(this);
		medGenName.setId(R.id.genName);
		medGenName.setText(textgenname);
		medGenName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
		ll.addView(medGenName,index);
		
		db.updateMedication(m, new Medication(textname, textgenname), currentUser);
		m=new Medication(textname, textgenname);
		
	}
	
	//changes text and icon of default CAB button
	private void customizeActionModeCloseButton() {
		int buttonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
		if (buttonId != 0)
		{
		    View v = findViewById(buttonId);
		    if (v != null)
		    {
		        LinearLayout ll = (LinearLayout)v;
		        View child = ll.getChildAt(1);
		        if (child != null)
		        {
		            TextView tv = (TextView)child;
		            tv.setText(R.string.cancel);
		        }
		        child = ll.getChildAt(0);
		        if (child != null)
		        {
			        ImageView iv = (ImageView) child;
			        Drawable cbutton = getResources().getDrawable(R.drawable.ic_action_cancel);
			        iv.setImageDrawable(cbutton);
		        }
		    }
		}
	}

	
	//adds a new dose
	@Override
	public void onPositiveClick(View view) {
		EditText e = (EditText)view.findViewById(R.id.amount);
 	   	String amount = (e.getText().toString());
 	   	e = (EditText)view.findViewById(R.id.type);
 	    String type = (e.getText().toString());
 	    TimePicker t = (TimePicker)view.findViewById(R.id.timePicker1);
 	    Dose d = new Dose(amount,type,t.getCurrentHour(),t.getCurrentMinute());
 	    //#### Here ####
 	    MedicationMonitor mm = new MedicationMonitor();
 	    mm.createNotification(m, d, this);
 	    //##############
 	    db.addDose(d, currentUser, m.getGenName());
 	    doses.add(d);
 	    doseStrings.add(doseStrings.size()-1, d.toString());
 	    adapter.notifyDataSetChanged();
 	    
	}


}

